package top.huntwolf.admin;

import com.alibaba.fastjson.JSON;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import springfox.documentation.spring.web.json.Json;
import top.huntwolf.admin.common.JsonResult;
import top.huntwolf.admin.dao.BookReserveDao;
import top.huntwolf.admin.dao.BookStorageDao;
import top.huntwolf.admin.dao.WxPayNotifyDao;
import top.huntwolf.admin.pojo.*;
import top.huntwolf.admin.pojo.cmsUser.RolePermission;
import top.huntwolf.admin.pojo.orderEntity.Order;
import top.huntwolf.admin.pojo.storage.BookStorage;
import top.huntwolf.admin.pojo.wxPay.WxPayNotify;
import top.huntwolf.admin.service.BookService;
import top.huntwolf.admin.service.CMSUserService;
import top.huntwolf.admin.service.OrderService;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
class AdminApplicationTests2 {

    @Value("${wechat.call-back-ip}")
    private String callbackip;


    @Value("${wechat.mchId}")
    private String merchantId;

    @Value("${wechat.mchSerialNo}")
    private String merchantSerialNumber;

    @Value("${wechat.apiV3Key}")
    private String apiV3Key;

    @Autowired
    private OrderService orderService;

    @Test
    void initChant() {
        PrivateKey merchantPrivateKey = null;
        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(
                    new FileInputStream("./path/to/apiclient_key.pem"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        // 获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        System.out.println(certificatesManager);

        // 向证书管理器增加需要自动更新平台证书的商户信息
        try {
            certificatesManager.putMerchant(merchantId, new WechatPay2Credentials(merchantId,
                    new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)), apiV3Key.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (HttpCodeException e) {
            e.printStackTrace();
        }

        // 从证书管理器中获取verifier
        Verifier verifier = null;
        try {
            verifier = certificatesManager.getVerifier(merchantId);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }

        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier));


        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        CloseableHttpClient httpClient = builder.build();

    }

    @Autowired
    private BookService bookService;

    @Test
    void test55(){
        WxPayNotify wxPayNotify = new WxPayNotify();
        wxPayNotify.setOut_trade_no("20220416981936101");
        Map<String,String> map = new HashMap<>();
        map.put("openid","oDfZz5XqQtVEFsgQRXhUwKSfDgrk");
        wxPayNotify.setPayer(map);

        Order order = orderService.queryStoreByOrder(wxPayNotify.getOut_trade_no(),wxPayNotify.getPayer().get("openid"));
        wxPayNotify.setStoreId(order.getStoreId());
        bookService.completeOrderIncrease(order);
    }

    @Autowired
    private WxPayNotifyDao wxPayNotifyDao;
    @Test
    void test2(){
        HashMap<String,String> map = new HashMap();
        map.put("openid","oDfZz5XqQtVEFsgQRXhUwKSfDgrk");
        orderService.generatePaymentOrder("202204111626230277",map.get("openid"));

//        HashMap map = new HashMap();
//        HashMap map1 = new HashMap();
//        map.put("openid","oDfZz5XqQtVEFsgQRXhUwKSfDgrk");
//        map1.put("payer_total","1");
//        map1.put("total","1");
//        map1.put("currency","CNY");
//        map1.put("payer_currency","CNY");
//
//        WxPayNotify wxPayNotify =new WxPayNotify("wx9939378be0b89e08","1617245874","20220411755127698","4200001323202204112374015544","JSAPI","SUCCESS","支付成功","OTHERS","","2022-04-11T22:01:56+08:00",map,map1,null,null);
//
//
//        System.out.println(wxPayNotify);
//        wxPayNotifyDao.insert(wxPayNotify);
    }

    @Test
    void test(){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://192.168.205.139:8988/address");
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("Content-type","application/json; charset=utf-8");
        CloseableHttpResponse response = null;
        try {

            Address address = new Address();

            address.setName("123");
            address.setOpenId("ongTV5DIEH1cvlP6cFQmmLh-hWg0");


            //设置请求体
            httpPost.setEntity(new StringEntity(JSON.toJSONString(address)));

            //执行请求
            response = httpClient.execute(httpPost);


            String bodyAsString = EntityUtils.toString(response.getEntity());
            System.out.println(bodyAsString);

        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Autowired
    private BookReserveDao reserveDao;

    @Autowired
    private BookStorageDao storageDao;


    @Test
    void test3(){

        List<BookReserve> bookReserveList = reserveDao.selectAll();

        List<BookStorage> bookStorages = new ArrayList<>();

        for (BookReserve br : bookReserveList){

            BookStorage bookStorage = new BookStorage().setStorage(br.getStorage()).setLocation("未整理").setIsbn(br.getIsbn());

            bookStorages.add(bookStorage);

        }
        storageDao.insert(bookStorages);


    }

    @Autowired
    private CMSUserService cmsUserService;

    @Test
    void test4(){

        //UPDATE book_reserve_1 SET location = '' WHERE location IS NULL
//        List<BookReserve> bookReserveList = reserveDao.selectAll();
//
//        List<BookStorage> bookStorages = new ArrayList<>();
//
//        for (BookReserve br : bookReserveList){
//
//            if(br.getLocation().equals(" ") ||br.getLocation()==null){
//                continue;
//            }
//
//            String[] s = br.getLocation().split(";");
//            for (String s1: s){
//                BookStorage bookStorage = new BookStorage().setLocation(s1).setIsbn(br.getIsbn()).setStorage(0);
//                bookStorages.add(bookStorage);
//            }
//
//        }
//        storageDao.insert(bookStorages);


    }
    }
